<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 商品品牌类
 * @package  htdocs
 * @subpackage  quanliadmin
 * @author   allen.qiang
 * @version 1.0
 */

class goodsBrand {

    private $dbca;

    public function __construct( $dbca ) {
        $this->dbca = $dbca;
    }

    /**
     * 查询商品品牌信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *      'page' => int 分页页码
     *      'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchGoodsBrand( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //品牌号
        if (isset($arg_array['brandID']) && is_numeric($arg_array['brandID'])) {
            $sql .= ' AND brandID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['brandID'];
        }

        //品牌名称
        if (isset($arg_array['brandName']) && !empty($arg_array['brandName'])) {
            $sql .= ' AND brandName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['s'] . '%';
        }

        //使用标志
        if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg'])) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_brand ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname'])) {
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);
                }


                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_brand ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'brandID' => $item->brandID,
                    'brandName' => $item->brandName,
                    'description' => $item->description,
                    'logo' => $item->logo ? G_IMAGE_URL . $item->logo : '',
                    'sortOrder' => $item->sortOrder,
                    'useFlg' => $item->useFlg,
                    'useName' => $item->useFlg ? '使用' : '禁用',
                    'tagID' => $item->tagID
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 新增或修改商品品牌信息
     * @param array $arg_array 品牌参数
     * @return array
     */
    public function editBrandInfo( $arg_array ) {

        //实例化公共类
        $commHandler = new commHandler();

        //实例化文件类
        $fileDirHandler = new fileDirHandler();

        //参数检查
        if (!isset($arg_array['brandName'] ,$arg_array['sortOrder'] , $arg_array['brand_img'],$arg_array['description'],$arg_array['useFlg'],
            $arg_array['operator']) || empty($arg_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误');
        }

        if (empty($arg_array['brandName'])) {
            return array( 'code' => 400, 'message' => '品牌名称不能为空');
        }

        if (!$commHandler->isInteger($arg_array['sortOrder'], 1)) {
            return array( 'code' => 400, 'message' => '排序序号必须为数字');
        }

        if (!in_array($arg_array['useFlg'], array(0, 1))) {
            $arg_array['useFlg'] = 1;
        }

        if (!isset($arg_array['brand_img']) || empty($arg_array['brand_img'])) {
            $arg_array['brand_img'] = null;
        }

        if (!isset($arg_array['brandID']) || empty($arg_array['brandID'])) {
            $arg_array['brandID'] = 0;
        }

        if (empty($arg_array['brand_img'])) {
            $oldName = null;
        } else {
            $oldName = G_APPLICATION_BASEPATH . $arg_array['brand_img'];
            $newName = G_IMAGE_SAVE_ROOT . 'brand/' . $fileDirHandler->basename($oldName);
        }

        $old_brand_log = null;

        try{

            $this->dbca->beginTransaction();

            //根据排序序号查询品牌信息
            $search_sql = 'SELECT brandID FROM goods_brand WHERE sortOrder = ?';
            $brand_array = &$this->dbca->stmt_query($search_sql, 'i', $arg_array['sortOrder']);

            //保存品牌信息
            $brand_obj = new entity('goods_brand');
            if ($arg_array['brandID'] > 0) {

                $brand_obj->brandID = $arg_array['brandID'];
                if (!$this->dbca->fetch($brand_obj)) {
                    throw new Exception('品牌信息没有找到', 404);
                }

                if ($brand_array && $brand_array[0]->brandID != $arg_array['brandID']) {
                    throw new Exception('排序序号已经被使用' , 404 ) ;
                }

                //更新商品列表里的品牌名称
                $this->dbca->stmt_query('UPDATE goods_list SET brandName=? WHERE brandID=?','si' , $arg_array['brandName'], $arg_array['brandID']) ;
                $this->dbca->stmt_query('UPDATE goods_list_edit SET brandName=? WHERE brandID=?','si' ,$arg_array['brandName'], $arg_array['brandID']) ;
                $this->dbca->stmt_query('UPDATE goods_sale SET brandName=? WHERE brandID=?','si' ,$arg_array['brandName'], $arg_array['brandID']) ;
                $this->dbca->stmt_query('UPDATE goods_sale_edit SET brandName=? WHERE brandID=?','si' ,$arg_array['brandName'], $arg_array['brandID']) ;

                $brand_obj->editor = $arg_array['operator'];
                $old_brand_log = $brand_obj->logo;

                //更新商品品牌标签
                $tag_array  = array(
                    'tagName'=> $arg_array['brandName'],
                    'tagID' => $brand_obj->tagID,
                    'tagGroupID' => BRAND_TAGGROUPID,
                    'creator' => $arg_array['operator']
                ) ;
                $resultData = $this->commPropertyTag ( $tag_array ) ;
                if($resultData['code'] == 400) {
                    throw new Exception($resultData['message'], 400 ) ;
                }


            } else {

                if ($brand_array) {
                    throw new Exception('排序序号已经被使用' , 404 ) ;
                }

                $brand_obj->creator = $arg_array['operator'];

                //生成标签组
                $tag_array  = array(
                    'tagName'=> $arg_array['brandName'],
                    'tagID' => 0,
                    'tagGroupID' => BRAND_TAGGROUPID,
                    'creator' => $arg_array['operator']
                ) ;
                $result_array = $this->commPropertyTag ($tag_array) ;
                if ($result_array['code'] == 200) {
                    $brand_obj->tagID = $result_array['message'];
                }

            }

            if (!empty($oldName)) {
                if (!$fileDirHandler->move($oldName, $newName)) {
                    throw new Exception('文件移动失败', 404);
                }
                $brand_obj->logo = 'brand/' . $fileDirHandler->basename($oldName);
            }
            $brand_obj->brandName = $arg_array['brandName'];
            $brand_obj->description = $commHandler->convertVar($arg_array['description']);
            $brand_obj->sortOrder = $arg_array['sortOrder'];
            $brand_obj->useFlg = $arg_array['useFlg'];
            $this->dbca->save( $brand_obj );

            $this->dbca->commit();

            if(!empty($old_brand_log)) {
                $fileDirHandler->unlink( G_IMAGE_SAVE_ROOT . $old_brand_log);
            }

            return array( 'code' => 200, 'message' => '品牌保存成功' );

        } catch( Exception $e ) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }

    }

    /**
     * 品牌的使用和禁用
     * @param array $arg_array 品牌参数
     * @return unknown
     */
    public function changeBrandUse ( $arg_array ) {

        //检查参数
        if (!isset($arg_array['brandID']) || !is_numeric($arg_array['brandID'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try{

            $brand_obj = new entity('goods_brand');
            $brand_obj->brandID = $arg_array['brandID'];
            if (!$this->dbca->fetch($brand_obj)) {
                throw new Exception('品牌信息没有找到', 404);
            }
            if ($brand_obj->useFlg) {
                $brand_obj->useFlg = 0;
            } else {
                $brand_obj->useFlg = 1;
            }
            $this->dbca->save($brand_obj);

            if ($brand_obj->useFlg) {
                return array( 'code' => 200, 'message' => '品牌启用成功' );
            } else {
                return array( 'code' => 200, 'message' => '品牌禁用成功' );
            }

        } catch( Exception $e ) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }


    /**
     * 删除品牌
     *
     */
    public function deleteBrand ( $arg_array ) {

        if (!isset($arg_array['b_array'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!isset($arg_array['b_array'][0])) {
            return array( 'code' => 400, 'message' => '请选择要删除的品牌' );
        }

        $delete_array = $arg_array['b_array'];

        $tag_id_str = '';

        try {

            //循环删除品牌
            foreach( $delete_array as &$brandID ) {

                //检查品牌是否为数字
                if (!is_numeric( $brandID )) {
                    throw new Exception('参数错误', 400);
                }

                //查询品牌信息
                $brand_obj = new entity('goods_brand');
                $brand_obj->brandID = $brandID;
                if ($this->dbca->fetch( $brand_obj )) {

                    $this->dbca->delete( $brand_obj );

                    if (empty($brand_obj->tagID)) {
                        continue;
                    }

                    if(empty($tag_id_str)) {
                        $tag_id_str .= $brand_obj->tagID;
                    } else {
                        $tag_id_str .= '_' . $brand_obj->tagID;
                    }

                }

            }

            //删除品牌标签
            $this->deleteTag(array('delete_str' => $tag_id_str)) ;

            return array( 'code' => 200, 'message' => '品牌删除成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }
    }

}